package cpr.name.videoenabledwebview;

import cpr.name.videoenabledwebview.utils.LogUtil;
import ohos.agp.components.AttrSet;
import ohos.agp.components.webengine.*;
import ohos.app.Context;
import ohos.media.image.PixelMap;

public class VideoEnabledWebView extends WebView {
    private static final String TAG = "VideoEnabledWebView";

    public VideoEnabledWebView(Context context) {
        super(context);
        init();
    }

    public VideoEnabledWebView(Context context, AttrSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        final WebConfig webConfig = getWebConfig();
        webConfig.setJavaScriptPermit(true);

        super.setWebAgent(new WebAgent() {
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                if (request == null || request.getRequestUrl() == null) {
                    LogUtil.info(TAG, "WebAgent isNeedLoadUrl:request is null.");
                    return false;
                }
                String url = request.getRequestUrl().toString();
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    webView.load(url);
                    return false;
                } else {
                    return super.isNeedLoadUrl(webView, request);
                }
            }

            @Override
            public void onLoadingContent(WebView webView, String url) {
                super.onLoadingContent(webView, url);
            }

            @Override
            public void onLoadingPage(WebView webView, String url, PixelMap icon) {
                super.onLoadingPage(webView, url, icon);
            }

            @Override
            public void onPageLoaded(WebView webView, String url) {
                super.onPageLoaded(webView, url);
            }

            @Override
            public void onError(WebView webView, ResourceRequest request, ResourceError error) {
                super.onError(webView, request, error);
                LogUtil.error(TAG, "onError");
            }
        });
    }
}
